package org.webscale.gae;

import java.util.logging.Logger;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;

public class TXManager {
	private static final Logger log = Logger.getLogger(TXManager.class
			.getName());

	private static TXManager self = new TXManager();
	private static final PersistenceManagerFactory pmfInstance =   JDOHelper.getPersistenceManagerFactory("transactions-optional");
	private static ThreadLocal<PersistenceManager> persistanceManagerThreadLocal = new ThreadLocal<PersistenceManager>();
	
	public static TXManager instance() {
		return self;
	}
	
    public static PersistenceManagerFactory get() {
	    return pmfInstance;
    }
	
	private TXManager() {
		super();
	}
	
	public void makePersistant(Object obj){
		getPM().makePersistent(obj);
	}
	
	public void start(){
		getCurrentTransaction().begin();
	}
	
	public void commit(){
		try
		{
			getCurrentTransaction().commit();
		} finally {
			if (getCurrentTransaction().isActive()) {
				log.warning("Trying to rollback transaction -BAD");
				getCurrentTransaction().rollback();
				persistanceManagerThreadLocal.set(null);
			}
		}
	}
	
	public Transaction getCurrentTransaction(){
    	return getPM().currentTransaction();
    }
	
    public PersistenceManager getPM(){
    	PersistenceManager pm = persistanceManagerThreadLocal.get();
    	if(pm== null){
    		pm = get().getPersistenceManager();
    		persistanceManagerThreadLocal.set(pm);
    	}
    	return pm;
    	
    }
    
    
}
